﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UtilTools
{
    public class PrintHelper
    {
        public static void ClassTestMethods<T>(T type, string keyWord = "test")
        {
            type.GetType().GetMethods().ToList()
            .Where(it => it.Name.Contains(keyWord, StringComparison.CurrentCultureIgnoreCase))
            .ToList().ForEach(it =>
            {
                it.Invoke(type, new object[0]);
                Console.WriteLine($"---------------------------{it.Name}---------------------------");
            });
        }

        /// <summary>
        /// 列对象打印
        /// </summary>
        /// <param name="list"></param>
        /// <typeparam name="T"></typeparam>
        public static void PrintList<T>(List<T> list) where T : class
        {
            list.ForEach(it => Console.WriteLine(PrintStr(it)));
        }

        /// <summary>
        /// 打印对象内所有属性信息
        /// </summary>
        /// <param name="t"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static string PrintStr<T>(T t) where T : class
        {
            StringBuilder sb = new StringBuilder();
            t.GetType().GetProperties().ToList().ForEach(it =>
            {
                var tempValue = it.GetValue(t);
                StringBuilder valueStr = new StringBuilder();
                if (it.PropertyType.IsGenericType && it.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    valueStr.Append(tempValue?.ToString());
                }
                else if (it.PropertyType.IsGenericType && tempValue != null)
                {
                    var slist = tempValue as IEnumerable;
                    foreach (var item in slist)
                    {
                        if (item == null)
                        {
                            continue;
                        }
                        valueStr.Append(PrintStr(item));
                    }
                    if ((tempValue as IList).Count > 0)
                    {
                        valueStr.Insert(0, "[").Append("]");
                    }
                    else
                    {
                        valueStr.Append("NULL");
                    }
                }
                else if (it.PropertyType.FullName.StartsWith("System."))
                {
                    valueStr.Append(tempValue?.ToString());
                }
                else if (tempValue != null)
                {
                    valueStr.Append(PrintStr(tempValue));
                }
                sb.Append($"{it.Name}:{valueStr.ToString().PadRight(10, ' ')}  ");
            });
            return $"{{{sb.ToString()}}}";
        }
    }
}
